/**
 * 引入mysql
 */
const mysql = require("mysql");
/**
 * 配置自己的mysql账号密码数据库名称
 */
const config = require("../db/config.ts");
/**
 * 使用连接池连接mysql
 * @type {Pool}
 */
const pool = mysql.createPool(config.mysql);

//中间件
const bodyParser = require("body-parser");

const jwt = require("jsonwebtoken");

//创建application/json解析
const jsonParser = bodyParser.json();

const fs = require("fs");
const multer = require("multer");
const path = require("path");
// 创建application/x-www-form-urlencoded
const urlencodedParser = bodyParser.urlencoded({ extended: false });

/**
 * 封装 promise 查询sql语句
 * @param sql
 * @param res
 * @returns {Promise<unknown>}
 */
const poolQuery = (sql, res) => {
  return new Promise((resolve, reject) => {
    pool.query(sql, function (err, result) {
      if (err) {
        console.log(err);
      }
      resolve(result);
    });
  });
};

/**
 * 随机取名
 * @returns {string}
 * @constructor
 */
const RandomName = () => {
  let str = "技师";
  let name = Math.floor(Math.random() * 999);
  return str + name + "号";
};
/**
 * 获取日期
 * @returns {string}
 */
const toTime = () => {
  var date = new Date();
  var nowDate =
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1) +
    "-" +
    date.getDate() +
    " " +
    date.getHours() +
    ":" +
    date.getMinutes() +
    ":" +
    date.getSeconds();
  return nowDate;
};
/**
 *  获取随机数
 * @param len
 * @returns {string}
 */
const randomString = (len) => {
  let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
  let strLen = chars.length;
  let randomStr = "";
  for (let i = 0; i < len; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * strLen));
  }
  return randomStr;
};
/**
 * 上传图片
 * @type {Multer}
 */
const uploadImg = multer({
  storage: multer.diskStorage({
    //设置文件存储位置
    destination: function (req, file, cb) {
      let date = new Date();
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let day = date.getDate();
      let dir = "./upload/Img/" + year + month + day;

      //判断目录是否存在，没有则创建
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, {
          recursive: true,
        });
      }
      //dir就是上传文件存放的目录
      cb(null, dir);
    },
    //设置文件名称
    filename: function (req, file, cb) {
      let fileName = Date.now() + path.extname(file.originalname);
      //fileName就是上传文件的文件名
      cb(null, fileName);
    },
  }),
});

module.exports = {
  RandomName,
  poolQuery,
  jsonParser,
  urlencodedParser,
  jwt,
  toTime,
  bodyParser,
  randomString,
  uploadImg,
};
